<template>
  <section>
    <el-input
      :placeholder="placeholder"
      v-model="userNames"
      :disabled="disabled"
      class="input-with-select"

    >
      <el-button slot="append" :disabled="disabled" type="primary" @click="showUserDialog">{{
        btnLabel
        }}
      </el-button>
    </el-input>
    <el-dialog
    :close-on-click-modal="false"
      custom-class="user_select_dialog"
      :title="title"
      append-to-body
      :width="width"
      ref="user_select_dialog"
      :visible.sync="sortDialogVisible"
      v-if="sortDialogVisible"
      destroy-on-close
    >
      <el-row :gutter="10">
        <el-col>
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane :label="tabConfigData.showAllOrganizeName" name="All"
                         v-if="tabConfigData.showAllOrganize"></el-tab-pane>
            <el-tab-pane :label="tabConfigData.showCustomOrganizeName" name="Ann"
                         v-if="tabConfigData.showCustomOrganize"></el-tab-pane>
            <el-tab-pane :label="tabConfigData.showAllWorkGroupName" name="WorkGroup"
                         v-if="tabConfigData.showAllWorkGroup"></el-tab-pane>
            <el-tab-pane :label="tabConfigData.showPersonalWorkGroupName" name="MyWorkGroup"
                         v-if="tabConfigData.showPersonalWorkGroup"></el-tab-pane>
          </el-tabs>
        </el-col>
        <el-col :span="10" style="min-width: 300px;">

          <el-form inline>
            <el-input placeholder="请输入内容" v-model="searchCondition.keyword" clearable>
              <el-button slot="append" icon="el-icon-search" @click="searchUser"></el-button>
            </el-input>
          </el-form>
          <div class="border_node_btn" style="height:480px;margin-top: 10px;">
            <el-tree
              :data="users"
              :show-checkbox="isMulSelect"
              default-expand-all
              node-key="uuid"
              ref="tree"
              class="left_tree"
              :filter-node-method="filterNode"
              highlight-current
              :expand-on-click-node=false
              @node-click="nodeClick"
              @check-change="leftCheckChange"
              :props="defaultProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <el-col :span="4" style="height: 500px; max-width:65px;display: table;">
          <div class="flex_box">


            <el-button
              :type=" leftSelectNode!==null?'primary':'info'"
              @click="confirmSelectUser"
              :class=""
              style="margin-top: 10px;margin-left: 0px;"
              :disable="leftSelectNode===null"
              icon="el-icon-arrow-right"
            >
            </el-button>
            <el-button
              :type=" rightSelectNode!==null?'primary':'info'"
              style="margin-top: 10px;margin-left: 0px;"
              @click="delSelectUser"
              :disable="rightSelectNode===null"
              icon="el-icon-arrow-left"
            >
            </el-button>
            <el-button
              type="primary"
              @click="allSelect"
              v-show="isMulSelect"
              :type=" containUser===0?'primary':'info'"
              style="margin-top: 10px;margin-left: 0px;"
              icon="el-icon-caret-right"
            >
            </el-button>
            <el-button
              type="primary"
              style="margin-top: 10px;margin-left: 0px;"
              icon="el-icon-caret-left"
              :type=" rightSelectUsers.length>0?'primary':'info'"
              @click="clearSelect"
            >
            </el-button>
          </div>
        </el-col>
        <el-col :span="rightSpan" ref="rightContent" :style="rightStyle">
          <el-form inline>
            <el-input placeholder="请输入内容" v-model="rightCondition">
              <el-button slot="append" icon="el-icon-search" @click="rightFilter"></el-button>
            </el-input>
          </el-form>
          <div class="border_node_btn" style=" height: 480px;margin-top: 10px;">

            <el-tree
              :data="rightSelectUsers"
              default-expand-all
              node-key="uuid"
              ref="rightTree"
              class="rightTree"
              highlight-current
              @node-click="nodeRightClick"
              :props="defaultRightProps">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                  <i :class="icoClass(data)"></i><span style="margin-left: 5px;">{{ data.name }}</span>  <span
                v-if="data.type!=='org'" style="margin-left: 10px;color:#cececd ">{{data.deptName?data.deptName:data.workGroupName}}</span>
                  <span style="margin-left: 10px;color:#cececd " v-if="containUser===1&&data.type==='org'">{{getCurNodeChildrenCount(data)}}人</span>
              </span>
            </el-tree>
          </div>
        </el-col>
      </el-row>
      <el-row style="margin-top: 10px;" v-if="containUser===1">
        <el-col>
          <span style="font-weight: bold;font-size: 18px;">总人数：</span> <span style="font-size: 18px;color: red;">{{totalCount}}人</span>
        </el-col>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="sortDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateUsers"
        >确 定</el-button
        >
      </span>
    </el-dialog>
  </section>
</template>

<script>
  import ArrayUtil from "@/libs/ArrayUtil";

  export default {
    name: "user-select",
    props: {
      value: '',
      width: {
        type: String,
        default: "50%"
      },
      title: {
        type: String,
        default: "选择组织机构和人员"
      },
      btnLabel: {
        type: String,
        default: "选择"
      },
      placeholder: {
        type: String,
        default: "请选择"
      },
      // 业务编码 null 使用页面属性的配置，否则根据key查询相应的配置
      businessKey: {
        type: String,
        default: null
      },
      // 用户范围
      userRange: {
        type: String,
        default: null
      },
      // 是否包含用户 0 不含，1包含
      containUser: {
        type: Number,
        default: 1
      },
      // 是否多选
      isMulSelect: {
        type: Boolean,
        default: false
      },
      // 是否禁用
      disabled: {
        type: Boolean,
        default: false
      },
      // 选择类型 0-部门/工作组，用户，1-用户，2-部门/工作组
      selectType: {
        type: Number,
        default: 0
      },
      // tab 配置
      tabConfig: {
        type: Object,
        default: null
      },

    },
    data() {
      return {
        isLoad: true,// 是否初始化加载
        userNames: "",
        userIds: '',
        rightCondition: '',
        rightSpan: 10,
        defaultProps: {
          children: 'children',
          label: 'name'
        },
        defaultRightProps: {
          children: 'list',
          label: 'name'
        },
        activeName: 'All',
        totalCount: 0,
        sortDialogVisible: false,
        searchCondition: {
          keyword: ""
        },
        users: [],
        rightSelectUsers: [],// 右侧选择的用户机构列表
        leftSelectNode: null,// 左侧点击选择对象
        rightSelectNode: null,// 右侧点击选择对象
        tabConfigData: {
          "showAllOrganize": true,
          "showCustomOrganize": false,
          "customOrganizeId": 0,
          "showAllWorkGroup": false,
          "showPersonalWorkGroup": false,
          "showAllOrganizeName": "全部",
          "showCustomOrganizeName": "公文传输",
          "showAllWorkGroupName": "工作组",
          "showPersonalWorkGroupName": "我的工作组"
        }
      }
    },
    // model: {
    //   prop: 'userIds',
    //   event: 'returnBack'
    // },
    computed: {
      rightStyle() {
        let me = this;
        let span = 10;
        this.$nextTick(function () {
          let dialog = me.$refs.user_select_dialog.$el
          let dialogBody = dialog.getElementsByClassName('el-dialog__body')
          let bodyWidth = dialogBody[0].clientWidth
          let one = (bodyWidth / 24)
          span = (bodyWidth - (one * 10 + 90)) / one
          me.rightSpan = Math.floor(span)
          me.$refs.rightContent.$el.style.width = Math.floor(bodyWidth - (one * 10 + 65) - 20) + "px"
          // if (me.isMulSelect) {
          //   // 设置左侧勾选状态
          //   console.log(me.$refs, me.$refs['tree'])
          //   this.$refs.tree.setCheckedNodes([])
          //   this.$refs.tree.setCheckedNodes(this.rightSelectUsers)
          // }
        })
      }
    },
    mounted() {
      console.log(this.userRange,'userRange')
      this.getTabConfig();
      if (this.value){
        if (this.value && this.value.length > 0) {
          this.userIds = this.value
          if (this.isLoad){
            this.updateDefaultUser()
          }
        }
      }
    },
    watch: {
      rightSelectUsers: {
        handler(val) {
          if (val && val.length > 0) {
            this.computeCount(val);
          }
        },
        deep: true
      },
      value: {
        handler(val) {
          if (val && val.length > 0) {
            this.userIds = val
            if (this.isLoad){
              this.updateDefaultUser()
            }
          }
        },
        deep: true
      }
    },
    methods: {
      // 根据业务编码获取tab的控制属性
      getTabConfig() {
        console.log(this.userRange,'userRange')
        if (this.userRange ===null||this.userRange === '' ||this.userRange === undefined){
          if (this.businessKey === null) {
            if (this.tabConfig) {
              Object.assign(this.tabConfigData, this.tabConfig)
            }
          } else {
            this.API.getModuleUserByKey({key: this.businessKey}).then(res => {
              Object.assign(this.tabConfigData, res.data)
            })
          }
          if (this.tabConfigData.showAllOrganize) {
            this.getOrganizeUser()
          } else {
            if (this.tabConfigData.showCustomOrganize) {
              this.getOrganizeUser(this.tabConfigData.customOrganizeId)
            } else {
              if (this.tabConfigData.showAllWorkGroup) {
                this.getWorkGroupUser(0)
              } else {
                if (this.tabConfigData.showPersonalWorkGroup) {
                  this.getWorkGroupUser(1)
                }
              }
            }
          }
        } else {
          this.getTreeListByIds()
        }

      },
      // 回显
      async updateDefaultUser() {
        this.userNames = ''
        this.rightSelectUsers = []
        if (this.userIds) {
          let tem = {type: this.containUser, parentId: 0}
          await this.API.getOrganizeTree(tem).then(async res => {
            let users = this.userIds.split(',')
            if (users && res.data) {
              let otherUsers = []
              users.map((item, index) => {
                let name = this.getUserNameById(res.data, item)
                if (name === undefined || name === null) {
                  otherUsers.push(item)
                } else {
                  if (index === users.length - 1 - otherUsers.length) {
                    this.userNames += name
                  } else {
                    this.userNames += (name + ",")
                  }
                }
              })
              if (otherUsers && otherUsers.length > 0) {
                await this.getNameByGroupData(otherUsers)
              }
            }
          })
        }
      },

      getNameByGroupData(otherUsers) {
        let temGroup = {type: this.containUser, parentId: 0, isMe: 0}
        this.API.getWorkGroupTree(temGroup).then(res => {
          if (res.data) {
            otherUsers.map((item, index) => {
              let name = this.getUserNameById(res.data, item)
              if (index === otherUsers.length - 1) {
                this.userNames += name
              } else {
                this.userNames += (name + ",")
              }
            })
          }
        })
      },

      getUserNameById(data, item) {
        for (let i = 0; i < data.length; i++) {
          let user = data[i]
          if (user.id === item) {
            this.rightSelectUsers.push(user)
            return user.name
          } else {
            if (user.children!==undefined) {
              let result = this.getUserNameById(user.children, item)
              if (result) {
                return  result;
              }
            }else {
              continue;
            }
          }
        }
      },

      // 获取当前节点的数量
      getCurNodeChildrenCount(data) {
        let tem = data.children.flatArr()
        let users = []
        if (tem) {
          tem.map((item) => {
            if (item.type !== 'org') {
              users.push(item)
            }
          })
        }
        return users.length;
      },
      // 右侧过滤
      rightFilter() {
        this.$refs.rightTree.filter(this.rightCondition);
      },
      // 计算选择人数
      computeCount(val) {
        let tem = val.flatArr()
        let users = []
        if (tem) {
          tem.map((item) => {
            if (item.type !== 'org') {
              users.push(item)
            }
          })
        }
        this.totalCount = users.length
      },
      // 右侧树点击
      nodeRightClick(data, node, self) {
        this.rightSelectNode = data
        console.log(data)
      },
      //根据类型获取图标
      icoClass(val) {
        if (val.type === 'org') {
          return "fa fa-folder";
        } else {
          return "fa fa-user";
        }
      },
      // 过滤用户
      searchUser() {
        this.$refs.tree.filter(this.searchCondition.keyword);
      },
      // 获取组织用户
      getTreeListByIds() {
        let tem = {ids: this.userRange+(this.value!==''?','+this.value:'')}
        this.API.getTreeListByIds(tem).then(res => {
          this.users = res.data
        })
      },
      // 获取组织用户
      getOrganizeUser(parentId) {
        let tem = {type: this.containUser, parentId: parentId === undefined ? 0 : parentId}
        this.API.getOrganizeTree(tem).then(res => {
          this.users = res.data
        })
      },
      // 获取工作组用户
      getWorkGroupUser(isMe) {
        let tem = {type: this.containUser, parentId: 0, isMe: isMe}
        this.API.getWorkGroupTree(tem).then(res => {
          this.users = res.data
        })
      },
      filterNode(value, data) {
        if (!value) return true;
        return data.name.indexOf(value) !== -1;
      },
      // tab切换
      handleClick(val) {
        console.log(val)
        this.activeName = val.name
        switch (val.name) {
          case 'All':
            this.getOrganizeUser();
            break;
          case 'Ann':
            this.getOrganizeUser(this.tabConfigData.customOrganizeId);
            break;
          case 'WorkGroup':
            this.getWorkGroupUser(0)
            break;
          case 'MyWorkGroup':
            this.getWorkGroupUser(1)
            break;
        }
      },
      // 树点击事件
      nodeClick(data, node, self) {
        this.leftSelectNode = data
      },
      //左侧多选事件
      leftCheckChange(data,self,node) {
        console.log(data,self,node)
        //如果取消选择，右侧去掉相关数据
        if(!self){
          this.rightSelectUsers.map((rightUser,index) => {
            if (rightUser.id === data.id) {
              this.rightSelectUsers.splice(index,1)
            }
          })
        }
        let depts=[]
        this.$refs.tree.getCheckedNodes().map(item => {
          if (item.type !== 'user') {
            depts.push(item)
          }
        })
        this.$refs.tree.getCheckedNodes().map(item => {
          if (item.type === 'user') {
            let existed = this.removeExistedUser(depts, item)
            if (!existed) {
              if (this.rightSelectUsers) {
                let existed = false
                this.rightSelectUsers.map((rightUser) => {
                  if (rightUser.id === item.id) {
                    existed = true
                  }
                })
                if (!existed) {
                  this.rightSelectUsers.push(item)
                }
              }
            }
          } else {
            if (this.rightSelectUsers) {
              let existed = false
              this.rightSelectUsers.map((rightUser) => {
                if (rightUser.id === item.id) {
                  existed = true
                }
              })
              if (!existed) {
                this.rightSelectUsers.push(item)
              }
            }
          }
        })
        // 右侧数据在去重复一次
        this.rightSelectUsers.map(item => {
          if (item.type !== 'user') {
            depts.push(item)
          }
        })
        this.rightSelectUsers.map((item,index) => {
          if (item.type === 'user') {
            let existed = this.removeExistedUser(depts, item)
            if (existed) {
              this.rightSelectUsers.splice(index, 1)
            }
          }
        })

      },



      // 递归遍历右侧选择的用户和部门以及部门下的子集，去除重复数据
      removeExistedUser(data, item) {
        let existed = false
        if (data) {
          data.map((rightUser) => {
            if (rightUser.id === item.id) {
              existed = true
            } else {
              if (rightUser.children) {
                existed= this.removeExistedUser(rightUser.children, item)
              }
            }
          })
        }
        return existed
      },
      // 展示用户弹出
      showUserDialog() {
        this.sortDialogVisible = true;
      },
      // 全选
      allSelect() {
        this.rightSelectUsers = this.users
      },
      // 清空
      clearSelect() {
        this.rightSelectUsers = []
      },
      // 确认选择的用户
      confirmSelectUser() {
        if (this.leftSelectNode) {
          if (this.selectType === 1 && this.leftSelectNode.type !== 'user') {
            this.warning("只能选择用户")
            return
          }
          if (this.selectType === 2 && this.leftSelectNode.type === 'user') {
            this.warning("请选择工作组或机构")
            return
          }
          if (!this.isMulSelect && this.rightSelectUsers.length > 0) {
            this.warning("只允许选择一个用户")
            return
          }
          console.log(this.leftSelectNode)
          let i = this.rightSelectUsers.indexOf(this.leftSelectNode)
          console.log(i)
          if (i !== -1) {
            this.warning(this.leftSelectNode.name + ",已存在相同数据")
          } else {

            this.rightSelectUsers.push(this.leftSelectNode);
            this.leftSelectNode = null
          }
        }
      },
      // 删除选择的用户
      delSelectUser() {
        if (this.rightSelectNode) {
          let i = this.rightSelectUsers.indexOf(this.rightSelectNode)
          this.rightSelectUsers.splice(i, 1);
          this.rightSelectNode = null;
        }
      },
      // 跟新组件值
      updateUsers() {
        let val = ''
        this.userNames = ''
        if (this.rightSelectUsers) {
          this.rightSelectUsers.map((item, index) => {
            if (index === this.rightSelectUsers.length - 1) {
              this.userNames += item.name
              val += item.id
            } else {
              this.userNames += (item.name + ",")
              val += (item.id + ",")
            }
          })
        }
        console.log(val, this.userNames)
        this.isLoad = false
        this.$emit('input', val)
        this.sortDialogVisible = false
      }
    }
  };
</script>

<style lang="less" scoped>
  .flex_box {
    display: table-cell;
    vertical-align: middle;
  }

</style>
